﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using WJP.Utils;

namespace WJP.Queue.Socketing
{
    /// <summary>
    /// Socket基础类
    /// </summary>
    public class SocketUtils
    {
        /// <summary>
        /// 获取本地IPV4地址
        /// </summary>
        /// <returns></returns>
        public static IPAddress GetLocalIPV4()
        {
            return Dns.GetHostEntry(Dns.GetHostName()).AddressList.First(x => x.AddressFamily == AddressFamily.InterNetwork);
        }

        /// <summary>
        /// 创建一个Socket
        /// </summary>
        /// <param name="sendBufferSize">发送缓冲区大小</param>
        /// <param name="receiveBufferSize">接收缓冲区大小</param>
        /// <returns></returns>
        public static Socket CreateSocket(int sendBufferSize, int receiveBufferSize)
        {
            var socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp)
            {
                NoDelay = true,
                Blocking = false,
                SendBufferSize = sendBufferSize,
                ReceiveBufferSize = receiveBufferSize
            };
            return socket;
        }

        /// <summary>
        /// 禁用发送和接收的Socket并关闭Socket连接
        /// </summary>
        /// <param name="socket"></param>
        public static void ShutdownSocket(Socket socket)
        {
            if (socket == null)
                return;

            Helper.EatException(() => socket.Shutdown(SocketShutdown.Both));
            Helper.EatException(() => socket.Close(10000));
        }

        /// <summary>
        /// 关闭Socket连接
        /// </summary>
        /// <param name="socket"></param>
        public static void CloseSocket(Socket socket)
        {
            if (socket == null)
                return;

            Helper.EatException(() => socket.Close(10000));
        }
    }
}
